package Part2_TCP;

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * ClassName: Demo
 * Package: IntelliJ IDEA
 * Description:
 * TCP:类似打电话
 * UDP:类似发短信
 * Written by HanXu
 * Create 2024.04.24 20:06
 */
public class Demo {

    //客户端
    @Test
    public void client() {

        OutputStream outputStream = null;
        Socket socket = null;

        try {
            //创建Socket
            InetAddress inet = InetAddress.getByName("192.168.195.246");//对方ip
            int port = 8089;//对方端口号
            socket = new Socket(inet, port);

            //发送数据
            outputStream = socket.getOutputStream();
            outputStream.write("客户端请求".getBytes(StandardCharsets.UTF_8));

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭Socket和Stream
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //服务端
    @Test
    public void server() throws IOException {


        //创建ServerSocket
        int port = 8089;
        ServerSocket serverSocket = new ServerSocket(port);

        //接受来自于客户端的Socket
        Socket socket = serverSocket.accept();//阻塞式的方法

        InetAddress inetAddress = socket.getInetAddress();
        System.out.println("收到了来自"+inetAddress.getHostName()+"的连接");//收到了来自Sherbledore的连接



        //接受数据
        InputStream inputStream = socket.getInputStream();

        int len;
        byte[] buffer = new byte[3];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//此对象内部维护了一个byte[]
        while ((len = inputStream.read(buffer)) != -1) {
            //new String()可能会出现乱码
            //System.out.print(new String(buffer, 0, len));
            baos.write(buffer, 0, len);//将buffer写入byte[]
        }
        System.out.println(baos);


        //关闭流、Socket、ServerSocket
        if (socket != null)
            socket.close();

        if (serverSocket != null)
            serverSocket.close();

        if (inputStream != null)
            inputStream.close();
    }
}
